package com.zshy.base.orm.typehandlers;

import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeReference;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 基础的String转换类型处理器
 *
 * @param <T>
 * @author zhouhengzhe
 */
public abstract class BaseStringTypeHandler<T> extends BaseTypeHandler<T> {

    public Class<T> type() {
        return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), this.getClass().getSuperclass(), 0);
    }


    /**
     * 获取实际的引用类型
     */
    public TypeReference<T> typeReference() {
        return new TypeReference<T>() {
        };
    }

    protected abstract String convert(T obj);

    protected abstract T parse(String result);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            return;
        }
        ps.setString(i, this.convert(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String str = rs.getString(columnName);
        return StringUtils.isBlank(str) ? null : this.parse(str);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        return StringUtils.isBlank(str) ? null : this.parse(str);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String str = cs.getString(columnIndex);
        return StringUtils.isBlank(str) ? null : this.parse(str);
    }
}
